//
//  ClassifyCtrl.swift
//  SwfitBase
//
//  Created by rubick on 2023/1/17.
//

import UIKit
import HandyJSON
import SwiftyJSON
import ZKProgressHUD
import SnapKit

class ClassifyCtrl: RKBaseCtrl, RKActivityViewable {
    //
    var tableView: UITableView!
    var channels: Array<ChannelModel?> = []
    //
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "豆瓣"
        view.backgroundColor = UIColor.white
        setupView()
        requestData()
    }
    func setupView() {
        tableView = UITableView(frame: CGRectZero, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableFooterView = UIView()
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCellId1")
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.width.height.equalTo(view)
            make.center.equalTo(view)
        }
    }
    func requestData() {
        startAnimating(type: .ballClipRotateMultiple)
        HJNetworkRequest(DouBanApi.channels) { result in
            self.stopAnimating()
            let channels = result["channels"] as! Array<Any>
            //
            if let channelList = [ChannelModel].deserialize(from: channels) {
                self.channels = channelList
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }
        } failed: { errorMsg, error in
            self.stopAnimating()
            ZKProgressHUD.showMessage(errorMsg)
        }
    }
}
extension ClassifyCtrl: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.channels.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCellId1", for: indexPath)
        cell.accessoryType = .disclosureIndicator
        let channel = self.channels[indexPath.row]!
        cell.textLabel?.text = channel.name
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let channel = self.channels[indexPath.row]!
        let channelId = channel.channelId!
        let temp = SongListCtrl()
        temp.channelId = "\(channelId)"
        temp.showTitle = channel.name
        self.navigationController?.pushViewController(temp, animated: true)
    }
}
